<?php

namespace App\Http\Controllers\Admin;

use App\Models\MemberAlipayRiskCredit;
use App\Models\MemberOther;
use App\Models\MemberQnRisk;
use App\Models\Order;
use App\Models\OrderCredit;
use App\Models\OtherOrder;
use App\Models\OtherOrderAllocate;
use App\Models\OtherOrderSet;
use App\Models\OtherOrderLog;
use App\Models\OrderGoods;
use App\Models\OrderLog;
use App\Models\OrderReturn;
use App\Models\ShopSms;
use App\Services\AlipayRiskService;
use App\Services\CommonService;
use App\Services\CreditCallService;
use App\Services\EsignService;
use App\Services\AlipayService;
use App\Services\CreditService;
use App\Services\OrderService;
use App\Services\RadarService;
use App\Services\SafeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NoticeController
{

    public function esignUserAuthCallNotify(Request $request){
        $request_data = $request->all();
        AlipayService::requestLog('用户授权协议授权书静默签署回调','',$request_data);


        $flow_id = $request_data['flowId'];
      sleep(8);
        $order = Order::where('flow_id_3',$flow_id)->select('id','pact_url_2','pact_url_3')->first();
        $order = $order ? $order->toArray() : [];


        //合同下载
        $return_content = EsignService::downloadDocument($flow_id);
        if($return_content && !empty($return_content['fileUrl'])&&$request_data['action']=='SIGN_FLOW_FINISH'){
            $fileUrl = $return_content['fileUrl'];
            $fileName = $flow_id.".pdf";
            $file = file_get_contents($fileUrl);
            $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/storage/tmp/'.$fileName;

            file_put_contents($path,$file);
            $uploud_res = AlipayService::upload($fileName,$path);
            if($uploud_res['status']){
                if(file_exists($path)){
                    unlink($path);
                }
            }
            $order_sign['pact_url_3'] = $fileName;

            Order::where('id',$order['id'])->update($order_sign);

            if($order['pact_url_3']){
                return DockingReturnMsg(CommonService::HTTP_CODE_SUCCESS,'成功');
            }
            $countRes=OrderCredit::where('order_id',$order['id'])->orderby('id','desc')->value('scoreNo');
            if($order['pact_url_2']&&!$countRes){
                $order = Order::from('sp_order_2 as o')->where('o.id',$order['id'])
                    ->leftjoin('sp_member_2 as m','m.id','o.uid')
                    ->select(
                        'o.id','o.uid','o.mobile as user_mobile','o.pact_url_2','o.trade_no'
                        ,'m.cert_name','m.cert_no','o.pact_url_3','m.mobile','m.esign_user_id','m.esign_seal_id','m.user_id','m.idcard_front','m.idcard_back'
                    )
                    ->first();
                $order = $order ? $order->toArray() : [];

                $risk_data = CreditCallService::getInvestData($order);

                OrderCredit::setRiskData($order['id'],$risk_data,$order['cert_name'],$order['mobile'],$order['cert_no']);
                Order::where('id',$order['id'])->update(['is_credit_select'=>'2']);
            }

            //上传到sftp
            // CreditService::login("rarmwl", "rarmwl@2023#03.10@",'https://img.qianbaozuji.com/'.$fileName,'/2023/'.$fileName);

            return DockingReturnMsg(CommonService::HTTP_CODE_SUCCESS,'成功');
        }else{
            return DockingReturnMsg(CommonService::HTTP_CODE_FAIL,'失败');
        }
    }
    /**
     * e签宝新征信个人信用报告授权书签署回调
     */
    public function esignUserAuthNotify(Request $request){
        $request_data = $request->all();
        AlipayService::requestLog('个人信用报告授权书静默签署回调','',$request_data);

        $flow_id = $request_data['flowId'];

        $order = Order::where('flow_id_2',$flow_id)->select('id','pact_url_3')->first();
        $order = $order ? $order->toArray() : [];

        //合同下载
        $return_content = EsignService::downloadDocument($flow_id);
        if($return_content && !empty($return_content['fileUrl'])){
            $fileUrl = $return_content['fileUrl'];
            $fileName = $flow_id.".pdf";
            $file = file_get_contents($fileUrl);
            $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/storage/tmp/'.$fileName;

            file_put_contents($path,$file);
            $uploud_res = AlipayService::upload($fileName,$path);
            if($uploud_res['status']){
                if(file_exists($path)){
                    unlink($path);
                }
            }
            $order_sign['pact_url_2'] = $fileName;

            Order::where('id',$order['id'])->update($order_sign);

//            if($order['pact_url_3']){
//                $order = Order::from('sp_order_2 as o')->where('o.id',$order['id'])
//                    ->leftjoin('sp_member_2 as m','m.id','o.uid')
//                    ->select(
//                        'o.id','o.uid','o.mobile as user_mobile','o.pact_url_2','o.trade_no'
//                        ,'m.cert_name','m.cert_no','o.pact_url_3','m.mobile','m.esign_user_id','m.esign_seal_id','m.user_id','m.idcard_front','m.idcard_back'
//                    )
//                    ->first();
//                $order = $order ? $order->toArray() : [];
//                $risk_data = CreditCallService::getInvestData($order);
//                OrderCredit::setRiskData($order['id'],$risk_data);
//                Order::where('id',$order['id'])->update(['is_credit_select'=>'2']);
//            }
            //上传到sftp
            // CreditService::login("rarmwl", "rarmwl@2023#03.10@",'https://img.qianbaozuji.com/'.$fileName,'/2023/'.$fileName);

            return DockingReturnMsg(CommonService::HTTP_CODE_SUCCESS,'成功');
        }else{
            return DockingReturnMsg(CommonService::HTTP_CODE_FAIL,'失败');
        }
    }

    /**
     * 征信查询回调
     */
    public function esignInvestNotify(Request $request){
        $request_data = $request->all();
        AlipayService::requestLog('征信查询回调','',$request_data);

        // $key = "650b51772746218ae039182f71f8e8a6";   //密钥-测试环境
        $key = "60f37b8c95d59225b0f0add06c2d1a39";   //密钥-线上环境
        $key16 = substr($key,0,16);
        if($request_data){
            $order_no = $request_data['order_no'];
            $name = CreditService::decrypt($request_data['name'],$key16);
            $id_card = CreditService::decrypt($request_data['id_card'],$key16);
            $response_info = CreditService::decrypt($request_data['response_info'],$key16);
            $credit_url = CreditService::decrypt($request_data['credit_url'],$key16);

            $editData = [
                'merchant_no'=>$request_data['merchant_no'], //商户号
                'cert_name'=>$name,
                'cert_no'=>$id_card,
                'result'=>$response_info,
                'credit_url'=>$credit_url,
                'signature'=>$request_data['signature'],
                'is_success'=>CreditService::RESULT_SUCCESS  //回调成功
            ];

            $res = OrderCreditNew::where('order_no',$order_no)->update($editData);

            AlipayService::requestLog('征信查询回调成功','',$res);

            return '征信查询回调成功';
        }else{

            AlipayService::requestLog('征信查询回调不成功','',$request_data);

            return '征信查询回调不成功';
        }

    }

    /**
     * e签宝征信静默授权协议签署回调
     */
    public function esignSlienceNotify(Request $request){
        $request_data = $request->all();
        AlipayService::requestLog('用户授权协议静默签署回调','',$request_data);

        $flow_id = $request_data['flowId'];

        $order = Order::where('flow_id_3',$flow_id)->select('id')->first();
        $order = $order ? $order->toArray() : [];

        //合同下载
        $return_content = EsignService::downloadDocument($flow_id);
        if($return_content && !empty($return_content['fileUrl'])){
            $fileUrl = $return_content['fileUrl'];
            $fileName = $flow_id.".pdf";
            $file = file_get_contents($fileUrl);
            $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/storage/tmp/'.$fileName;

            file_put_contents($path,$file);
            $uploud_res = AlipayService::upload($fileName,$path);
            if($uploud_res['status']){
                if(file_exists($path)){
                    unlink($path);
                }
            }
            $order_sign['pact_url_3'] = $fileName;

            Order::where('id',$order['id'])->update($order_sign);
            //上传到sftp
            CreditService::login("rarmwl", "rarmwl@2023#03.10@",'https://img.qianbaozuji.com/'.$fileName,'/2023/'.$fileName);

            return DockingReturnMsg(CommonService::HTTP_CODE_SUCCESS,'成功');
        }else{
            return DockingReturnMsg(CommonService::HTTP_CODE_FAIL,'失败');
        }
    }

    /**
     * e签宝征信融资租赁委托担保合同回调
     */
    public function esignCompanyNotify(Request $request){
        $request_data = $request->all();
        AlipayService::requestLog('融资租赁委托担保合同静默签署回调','',$request_data);

        $flow_id = $request_data['flowId'];

        $order = Order::where('flow_id_4',$flow_id)->select('id')->first();
        $order = $order ? $order->toArray() : [];

        //合同下载
        $return_content = EsignService::downloadDocument($flow_id);
        if($return_content && !empty($return_content['fileUrl'])){
            $fileUrl = $return_content['fileUrl'];
            $fileName = $flow_id.".pdf";
            $file = file_get_contents($fileUrl);
            $path = dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/storage/tmp/'.$fileName;

            file_put_contents($path,$file);
            $uploud_res = AlipayService::upload($fileName,$path);
            if($uploud_res['status']){
                if(file_exists($path)){
                    unlink($path);
                }
            }
            $order_sign['pact_url_4'] = $fileName;

            Order::where('id',$order['id'])->update($order_sign);

            return DockingReturnMsg(CommonService::HTTP_CODE_SUCCESS,'成功');
        }else{
            return DockingReturnMsg(CommonService::HTTP_CODE_FAIL,'失败');
        }
    }
    /**
     * e签宝征信融资租赁委托担保合同回调
     */
    public function junxinNotify(Request $request){
        $request_data = $request->all();
        AlipayService::requestLog('钧信融资租赁委托担保合同回调','',$request_data);
        $code = $request_data['data']['code'];
        $platformLoanNo = $request_data['data']['platformLoanNo'];
        $guaranteeAgreementFile = $request_data['data']['guaranteeAgreementFile'];
        if($code == 0){
            //更新合同
            $updateData = [
                    'guaranteeAgreementFile'=>"data:application/pdf;base64,".$guaranteeAgreementFile
                ];
            OrderCredit::where('platformLoanNo',$platformLoanNo)->update($updateData);

        }
    }





}
